import 'package:flutter/material.dart';
import 'package:flutter_demo/components/tiny_video_card.dart';
import 'package:flutter_demo/models/video_model.dart';
import 'package:flutter_demo/services/video_service.dart';
import 'package:flutter_easyrefresh/easy_refresh.dart';

class TinyVideoPage extends StatefulWidget {
  @override
  _TinyVideoPageState createState() => _TinyVideoPageState();
}

class _TinyVideoPageState extends State<TinyVideoPage>
    with AutomaticKeepAliveClientMixin {
  // 下拉刷新控制器
  EasyRefreshController _easyRefreshController;

  List<VideoItem> _videoList = VideoList([]).list;
  int page = 1;
  int limit = 10;
  bool hasMore = true;
  bool error = false;
  String errorMsg;

  @override
  void initState() {
    super.initState();

    _easyRefreshController = EasyRefreshController();

    _getVideos();
  }

  // 获取数据
  Future _getVideos({bool push = false}) async {
    try {
      // 获取数据
      Map<String, dynamic> result = await VideoService.getVideos(page: page);
      // 将数据转为实体类
      VideoList videoListModel = VideoList.fromJson(result['data']);

      setState(() {
        hasMore = page * limit < result['total'];
        page++;

        if (push) {
          _videoList.addAll(videoListModel.list);
        } else {
          _videoList = videoListModel.list;
        }
      });
    } catch (e) {
      // print(e);

      setState(() {
        error = true;
        errorMsg = e.toString();
      });
    }
  }

  // 下拉刷新
  Future _onRefresh() async {
    page = 1;
    await _getVideos();
    // 完成刷新
    _easyRefreshController.finishRefresh();
    // 重置刷新组件插件状态
    _easyRefreshController.resetLoadState();
  }

  // 上拉加载
  Future _onLoad() async {
    if (hasMore) {
      await _getVideos(push: true);
    }
    // 完成加载
    _easyRefreshController.finishLoad(noMore: !hasMore);
  }

  @override
  Widget build(BuildContext context) {
    super.build(context);
    return EasyRefresh(
      controller: _easyRefreshController,
      enableControlFinishLoad: true,
      enableControlFinishRefresh: true,
      onLoad: _onLoad,
      header: ClassicalHeader(),
      footer: ClassicalFooter(),
      onRefresh: _onRefresh,
      child: _buildBody(),
    );
  }

  Widget _buildBody() {
    return GridView.builder(
      itemCount: _videoList.length,
      itemBuilder: (BuildContext context, int index) {
        bool isEven = index.isEven;
        double pl = isEven ? 18 : 9;
        double pr = isEven ? 9 : 18;
        return Container(
          padding: EdgeInsets.only(top: 18, left: pl, right: pr),
          color: Colors.white,
          child: TinyVideoCard(
            videoItem: _videoList[index],
          ),
        );
      },
      padding: EdgeInsets.only(top: 8),
      gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
        crossAxisSpacing: 4,
        mainAxisSpacing: 8,
        crossAxisCount: 2,
        childAspectRatio: 1 / 2,
      ),
    );
  }

  @override
  bool get wantKeepAlive => true;
}
